<?php

namespace App\Server\Wxapp;

class Pay {

    private $payConfig = [];
    private $app = null;

    public function __construct()
    {
        $this->payConfig = config('wxpay');
        $this->app = new \EasyWeChat\Pay\Application($this->payConfig); 
    }

    /**
     * 
     * 统一下单
     * 
     */
    public function transaction($openId, $amount, $outTradeNo, $desc, $notifyUrl)
    {
        $data = [
            "mchid" => $this->payConfig["mch_id"],
            "out_trade_no" => $outTradeNo,
            "appid" => env("Wxapp_appid"),
            "description" => $desc,
            "notify_url" => $notifyUrl,
            "amount" => [
                "total" => (int)$amount,
                "currency" => "CNY"
            ],
            "payer" => [
                "openid" => $openId,
            ]
        ];
        $response = $this->app->getClient()->postJson("v3/pay/transactions/jsapi", $data);
        $prePayId = $response->toArray(false);
        $utils = $this->app->getUtils();
        $prepayId = $prePayId['prepay_id'];
        $appId = $params['appid'];
        $signType = "RSA";
        return $utils->buildMiniAppConfig($prepayId, env("Wxapp_appid"), $signType);
    }

    /**
     * 
     * 支付通知
     * $message->out_trade_no 获取商户订单号
     * $message->payer['openid'] 获取支付者 openid
     * 
     */
    public function paidNotify(callable $callback)
    {
        $server = $this->app->getServer();
        $server->handlePaid(function (Message $message, \Closure $next) {
            $callback($message['out_trade_no'], $message['transaction_id']);
            return $next($message);
        });
        return $server->serve();
    }

    /**
     * 
     * 退款通知
     * 
     */
    public function refundedNotify(callable $callback)
    {
        $server = $app->getServer();
        $server->handleRefunded(function (Message $message, \Closure $next) { 
            $callback($message['out_trade_no'], $message['transaction_id']);
            return $next($message);
        });
        return $server->serve();
    }

}